<template>
	<view class="stepper">
		<view class="stepper-lable">数量</view>
		<view class="stepper-field">
			<view
				class="iconfont icon-shangpinshuliang-jian"
				:class="{ disabled: disableMinus }"
				@click="onMinus">
			</view>
			<input v-model="numData" @input="onInputNum">
			<view
				class="iconfont icon-shangpinshuliang-jia"
				:class="{ disabled: disablePlus }"
				@click="onPlus">
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			num: {
				type: [Number, String],
				default: 1
			},
			minNum: {
				type: [Number, String],
				default: 1
			},
			maxNum: {
				type: [Number, String],
				default: 1
			}
		},
		data () {
			return {
				numData: this.num
			}
		},
		computed: {
			disableMinus () {
				return this.numData === this.minNum
			},
			disablePlus () {
				return this.numData >= this.maxNum
			}
		},
		methods: {
			onMinus () {
				if (this.disableMinus) {
					return false
				}
				this.numData--
				this.$emit('change-num', this.numData)
			},
			onPlus () {
				if (this.disablePlus) {
					return false
				}
				this.numData++
				this.$emit('change-num', this.numData)
			},
			onInputNum (e) {
				const value = e.detail.value
				let rs = ''
				const reg = /^\d*$/
				for (let i = 0; i < value.length; i++) {
					const char = value[i]
					if (reg.test(char)) {
						rs += char
					}
				}
				if (rs) {
					if (rs > this.maxNum) {
						rs = this.maxNum
					}
				} else {
					rs = this.minNum
				}
				this.$nextTick(() => {
					this.numData = rs
					this.$emit('change-num', this.numData)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.stepper {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		margin-top: 36rpx;
		&-lable {
			font-size: 30rpx;
			color: #999;
		}
		&-field {
			display: flex;
			align-items: center;
			height: 54rpx;
			
			.iconfont {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 84rpx;
				height: 100%;
				font-size: 24rpx;
				&.disabled {
					color: #dedede;
				}
			}
			
			input {
				width: 84rpx;
				color: #282828;
				font-size: 32rpx;
				line-height: 1.4em;
				text-align: center;
				background: #f2f2f2;
				    
			}
		}
	}
</style>
